import store from '@/store'
import {routes} from './whiteList'
const customRouter = (function() {
	let error = null;
	const findPage = (path) => {
		const pages = getCurrentPages().map((t) => `/${t.route}`);
		if (pages.length >= 9) {
			error = new Error(
				`页面栈已满，最大值：10，当前值：${pages.length}。\n CurrentPages:${pages}，已自动采用redirectTo做为跳转`)
			return -9999;
		}
		const index = pages.indexOf(path)
		return index !== -1 ? pages.length - (index != 0 ? index : 1) : -1;
	}
	const findWhite = (url) => {
		const originUrl=url.split('?');
		return (store.state.userInfo.userAuth == 'success' || routes.indexOf(originUrl[0])!=-1)
	}
	return {
		navigateTo: (options) => {
			const whith = findWhite(options.url);
			console.log(options.url);
			if (!whith) {
				if (store.state.userInfo.userAuth == 'notAuth') {
					options.url = '/pages/tabbar/user/user?popup=true'
					uni.reLaunch(options)
					return
				} else {
					options.url = '/loginPackages/wxLogin/wxLogin'
				}
			}
			const router = findPage(options.url);
			if (router === -1) {
				uni.navigateTo(options)
			} else if (router === -9999) {
				uni.redirectTo(options)
			} else {
				if (router == 0) return
				uni.navigateBack({
					delta: router
				})
			}
		},
		navigateBack: (options) => {
			uni.navigateBack(options)
		},
		redirectTo: (options) => {
			uni.redirectTo(options)
		},
		reLaunch: (options) => {
			uni.reLaunch(options)
		},
		switchTab: (options) => {
			uni.switchTab(options)
		}
	}
}())
export default customRouter